// 引入数据库模型
const User = require("../model/User");
const MedicalRecord = require("../model/MedicalRecord");
// 登录
async function login(userData) {
  // 从数据库中查找
  const user = await User.findOne(userData);
  // 是否找到
  if (user != null) {
    return user;
  } else {
    return false;
  }
}
// 获取用户列表
async function getUserList(data) {
  const result = await User.find(data);
  if (result) {
    return result;
  } else {
    return "error";
  }
}

// 添加用户
async function register(params) {
  const isHas = await User.findOne({ phone: params.phone });
  if (!isHas) {
    params.headImg = "https://yydy.love/Resouce/tom.jpg";
    params.username =
      `user` + parseInt(Math.random() * (100000 - 10000) + 10000);
    const result = await User.create(params);
    return true;
  } else {
    return false;
  }
}
// 重置密码
async function update(params) {
  const { phone, password } = params;
  const res = await User.findOne({ phone });
  if (res) {
    const result = await User.updateOne({ phone }, { password });
    if (result) {
      return "重置密码成功";
    } else {
      return "重置密码失败";
    }
  } else {
    return "请确认是否注册";
  }
}

async function userAuth(params) {
  const { phone } = params;
  const result = await User.updateMany({ phone }, params);
  if (result !== null) {
    return true;
  } else {
    return false;
  }
}
// 获取病历列表
async function getMedicalList(params) {
  const result = await MedicalRecord.find(params);
  if (result !== null) {
    return result;
  } else {
    return false;
  }
}

// 导出
module.exports = {
  login,
  getUserList,
  register,
  update,
  userAuth,
  getMedicalList,
};
